<template>
  <el-card class="template-card">
    <template #header>
      <div class="card-header">
        <span>题型表单模板配置</span>
        <el-button type="primary" @click="handleSaveTemplate">保存模板</el-button>
      </div>
    </template>

    <div class="template-config">
      <el-form :model="templateConfig" label-width="120px">
        <el-form-item label="题型">
          <el-select v-model="selectedTypeId" @change="loadTemplate" placeholder="请选择题型">
            <el-option
              v-for="type in questionTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div v-if="selectedTypeId" class="form-builder">
        <h3>拖拽配置区域</h3>
        <div class="draggable-items">
          <div class="item" draggable="true" @dragstart="drag($event, 'content')">
            题干内容
          </div>
          <div class="item" draggable="true" @dragstart="drag($event, 'options')">
            选项设置
          </div>
          <div class="item" draggable="true" @dragstart="drag($event, 'answer')">
            答案设置
          </div>
          <div class="item" draggable="true" @dragstart="drag($event, 'image')">
            题目图片
          </div>
          <div class="item" draggable="true" @dragstart="drag($event, 'htmlContent')">
            富文本题干
          </div>
          <div class="item" draggable="true" @dragstart="drag($event, 'htmlAnswer')">
            富文本答案
          </div>
          <div class="item" draggable="true" @dragstart="drag($event, 'imageAnswer')">
            答案图片
          </div>
          <div class="item" draggable="true" @dragstart="drag($event, 'points')">
            分值设置
          </div>
          <div class="item" draggable="true" @dragstart="drag($event, 'difficulty')">
            难度设置
          </div>
          <div class="item" draggable="true" @dragstart="drag($event, 'tags')">
            知识点标签
          </div>
          <div class="item" draggable="true" @dragstart="drag($event, 'source')">
            题目来源
          </div>
        </div>

        <div class="drop-zone" @drop="drop" @dragover="allowDrop">
          <div class="drop-placeholder" v-if="templateConfig.fields.length === 0">
            请将需要的字段拖拽到此区域
          </div>
          <div 
            v-for="(field, index) in templateConfig.fields" 
            :key="index" 
            class="dropped-field"
          >
            <el-tag closable @close="removeField(index)">
              {{ getFieldLabel(field) }}
            </el-tag>
          </div>
        </div>

        <div class="preview-section">
          <h3>预览</h3>
          <div class="form-preview">
            <el-form label-width="120px">
              <template v-for="(field, index) in templateConfig.fields" :key="index">
                <el-form-item :label="getFieldLabel(field)">
                  <component :is="getFieldComponent(field)" />
                </el-form-item>
              </template>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import questionTypesService from '../../services/questionTypes'

// 数据定义
const questionTypes = ref([])
const selectedTypeId = ref('')
const templateConfig = ref({
  typeId: '',
  fields: []
})

// 字段标签映射
const fieldLabels = {
  content: '题干内容',
  options: '选项设置',
  answer: '答案设置',
  image: '题目图片',
  htmlContent: '富文本题干',
  htmlAnswer: '富文本答案',
  imageAnswer: '答案图片',
  points: '分值设置',
  difficulty: '难度设置',
  tags: '知识点标签',
  source: '题目来源'
}

// 获取字段标签
const getFieldLabel = (field) => {
  return fieldLabels[field] || field
}

// 获取字段对应的组件
const getFieldComponent = (field) => {
  switch (field) {
    case 'content':
      return 'el-input'
    case 'options':
      return 'el-input'
    case 'answer':
      return 'el-input'
    case 'image':
      return 'el-upload'
    case 'htmlContent':
      return 'el-input'
    case 'htmlAnswer':
      return 'el-input'
    case 'imageAnswer':
      return 'el-upload'
    case 'points':
      return 'el-input-number'
    case 'difficulty':
      return 'el-rate'
    case 'tags':
      return 'el-select'
    case 'source':
      return 'el-cascader'
    default:
      return 'el-input'
  }
}

// 拖拽开始
const drag = (ev, field) => {
  ev.dataTransfer.setData("field", field)
}

// 允许放置
const allowDrop = (ev) => {
  ev.preventDefault()
}

// 放置处理
const drop = (ev) => {
  ev.preventDefault()
  const field = ev.dataTransfer.getData("field")
  if (!templateConfig.value.fields.includes(field)) {
    templateConfig.value.fields.push(field)
  }
}

// 移除字段
const removeField = (index) => {
  templateConfig.value.fields.splice(index, 1)
}

// 加载题型列表
const loadQuestionTypes = async () => {
  try {
    const response = await questionTypesService.fetchQuestionTypes()
    questionTypes.value = response.data
  } catch (error) {
    ElMessage.error('加载题型列表失败: ' + error.message)
  }
}

// 加载模板
const loadTemplate = async () => {
  try {
    templateConfig.value.typeId = selectedTypeId.value
    const template = await questionTypesService.getFormTemplate(selectedTypeId.value)
    templateConfig.value.fields = template.fields || []
  } catch (error) {
    ElMessage.error('加载模板配置失败: ' + error.message)
    templateConfig.value.fields = []
  }
}

// 保存模板
const handleSaveTemplate = async () => {
  if (!selectedTypeId.value) {
    ElMessage.warning('请先选择题型')
    return
  }
  
  try {
    const formTemplate = {
      fields: templateConfig.value.fields
    }
    
    await questionTypesService.saveFormTemplate(selectedTypeId.value, formTemplate)
    ElMessage.success('模板配置已保存')
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message)
  }
}

// 初始化
onMounted(() => {
  loadQuestionTypes()
})
</script>

<style scoped>
.template-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.draggable-items {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.item {
  padding: 8px 16px;
  background-color: #ecf5ff;
  border: 1px solid #409eff;
  border-radius: 4px;
  cursor: move;
  user-select: none;
}

.drop-zone {
  min-height: 100px;
  border: 2px dashed #409eff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.drop-placeholder {
  color: #909399;
  text-align: center;
  line-height: 60px;
}

.dropped-field {
  display: inline-block;
  margin: 5px;
}

.form-preview {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
  background-color: #f5f7fa;
}
</style>